package com.imb.common.web.jackson;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.imb.common.mybatis.entity.ImbUser;
import com.imb.common.web.model.LoginUser;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.TimeZone;

import static com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping.NON_FINAL;

/**
 * @author xzhi
 * @desc
 * @date 2024-09-24
 */
@Configuration
@Slf4j
public class JacksonConfig {

    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //控制是否在序列化时包裹根值，默认为 false。
        objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        //控制输出的 JSON 是否缩进，便于阅读，默认为 false
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        //控制日期类型的序列化方式，默认为 true（序列化为时间戳）
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //控制反序列化时遇到未知属性是否抛出异常，默认为 true。
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //注意：当bean没有属性时产生空的对象而不是报错
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        //控制单个值是否可以被视为数组，默认为 false。
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        //设置属性命名策略，如转换为小写、大写等。
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
        //激活默认类型处理，用于处理多态类型。
//        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, NON_FINAL);
        //自动注册java时间模块
//        objectMapper.findAndRegisterModules();
        objectMapper.registerModules(buildJavaTimeModule());
        //序列换成json时,将所有的long变成string.因为js中得数字类型不能包含所有的java long值，超过16位后会出现精度丢失
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        // 添加其他配置项...
        return objectMapper;
    }

    public static void main(String[] args) throws Exception {
        ImbUser user = new ImbUser();
        user.setCreateTime(LocalDateTime.now());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(buildJavaTimeModule()); // 使用 JavaTimeModule 自动处理日期时间格式化
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//        mapper.findAndRegisterModules();
//        SimpleModule simpleModule = new SimpleModule();
//        simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER));
//        simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER));
//        mapper.registerModules(simpleModule);
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
//        System.out.println(new JacksonConfig().jacksonObjectMapper().writeValueAsString(user));
    }

//    @Bean
    private static JavaTimeModule buildJavaTimeModule() {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DatePattern.NORM_TIME_FORMATTER));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER));
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER));

        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DatePattern.NORM_TIME_FORMATTER));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER));
        return javaTimeModule;
    }

    @Bean
    public Module javaTimeModule() {
        JavaTimeModule module = new JavaTimeModule();
        // 为 LocalDateTime 设置自定义序列化器
        LocalDateTimeSerializer localDateTimeSerializer = new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER);
        LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER);
        module.addSerializer(LocalDateTime.class, localDateTimeSerializer);
        module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
        return module;
    }

    /**
     * 第二种
     * @return
     */
//    @Bean
//    @ConditionalOnMissingBean
//    public Jackson2ObjectMapperBuilderCustomizer customizer() {
//        log.info("[Jackson2ObjectMapperBuilderCustomizer][初始化customizer配置]");
//        return builder -> {
//            builder.locale(Locale.CHINA);
//            builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
//            builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
//            builder.serializerByType(Long.class, ToStringSerializer.instance);
//            builder.modules(buildJavaTimeModule());
//        };
//    }

}
